<!-- 编目初审终审 -->
<script lang="ts" setup>
import { ref, reactive, onMounted, shallowRef, watch, toRaw } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NFormItem,
  NInput,
  NScrollbar,
  NSpin,
  NDataTable,
  NModal,
  useMessage,
  NImageGroup,
  NImage,
  type DataTableColumns
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import VDisOrEnd from '@/views/OA/Common/DisOrEnd.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import useSubmit,{defaultVersionTypeValue,defaultVersionTypeKey} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
const { dfInst, formData:formData1, createVars,submitLoading,submit:submitR } = useSubmit()
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 }, //1审核2 审核退回
  code: { type: String, default: () => null },
  idSelf: { type: String, default: () => null }
})
const message = useMessage()
const tableData1 = ref()
const tableData2 = ref() //终审table数据
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const array = props?.id?.split(',') || []
const form: any = reactive({
  id: route.query.id,
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null
  }
})
const formInst = ref<FormInst | null>(null)
const formData = ref({} as any)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    const { data } = res
    // formData.value = Object.assign(
    //   {},
    //   {
    //     itemName: data.itemName,
    //     receiveTime: data.receiveTime,
    //     itemTypeCode: data.itemTypeCode,
    //     itemTypeName: data.itemTypeName,
    //     collectTypeName: data.collectTypeName,
    //     itemNum: data.itemNum,
    //     receiveUser: data.receiveUser,
    //     notes: data.notes,
    //     itemTypeItem: data.itemTypeName
    //   },
    //   JSON.parse(data.jsonStr || '{}')
    // )
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const otherJson = ref({} as ModelJson)
const fileImgList:any = ref([])
const getInfo = async () => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: route.query?.code
    }
  }).then(async ([err, res]) => {
    if (err) return
    keysOf(res.data.detailVo).forEach((e) => {
      form[e] = res.data[e] as never
    })
    console.log(res.data)
    res.data?.collectingItems?.fileList?.map((i: any) => {
      fileImgList.value.push({
        name: i.name,
        url: i.path,
        status: 'finished',
        id: i.id
      })
    })
    // queryJsonBM(res.data?.detailVo?.itemTypeCode)
    checkIsDetail(res.data?.detailVo?.itemCode)
    formData1.value = JSON.parse(res.data?.catalogInfo || `{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`)
  })
}
const getFlowFn1 = () => {
  sendRequest({
    module: 'collectProcess',
    api: 'infoFinalAuditRecord',
    uri: {
      subItemCode: route.query?.code
    }
  }).then(async ([err, res]) => {
    if (err) return
    
    form.status = res.data[0]?.status
    form.workflow = res.data[0]?.workflow
    tableData1.value = res.data[0]?.approvalRecordsList || []
    form.assigneeFlag = res.data[0]?.assigneeFlag
    form.status1 = res.data[1]?.status
    form.workflow1 = res.data[1]?.workflow
    tableData2.value = res.data[1]?.approvalRecordsList || []
    
    form.fromId = res.data?.pop()?.fromId
  })
}

watch(
  () => route.query.id,
  () => {
    if (route.query.id) {
      fileImgList.value = []
      getInfo()
      // getFlowFn()
      getFlowFn1()
    }
  },
  {
    immediate: true
  }
)
const columns1: DataTableColumns = [
  {
    title: '类型',
    key: 'type',
    width: 50
  },
  {
    title: '人员',
    key: 'userName',
    width: 50
  },
  {
    title: '时间',
    key: 'time',
    width: 100
  },
  {
    title: '结果',
    key: 'result',
    width: 50
  },
  {
    title: '备注',
    key: 'remark',
    width: 150
  }
]
const modalVisible = ref(false)
const beforeBack =()=>{
  form.remarkResult = null
  modalVisible.value = true
}

const againBack = async () => {
  if(!form.remarkResult) return message.info('请填写审核退回原因')
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectItemsAssessfinalAuditBack',
    override: {
      data: {
        reviewOpinions: form.remarkResult,
        subItemCode: route.query?.code
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  modalVisible.value = false
  routeReplace()
  
}
</script>

<template>
  <DetailFormProvider>
    <div class="main">
      <div class="form_content">
        <NScrollbar>
          <NSpin :show="false">
            <div class="content">
              <div v-if="route.query?.typeShow == 2" style='margin-bottom:10px'>
                <NButton
                  style="width: 78px; color: red"
                  ghost
                  type="error"
                  @click="beforeBack"
                >
                  审核退回
                </NButton>
              </div>
              <VDisOrEnd
                :id="form?.fromId"
                :assigneeFlag="form?.assigneeFlag"
                title=""
                v-else
              ></VDisOrEnd>
            <div class="dynamic-form-demo">
          <DynamicFormComponent ref="dfInst" :disabled="true" v-if='formData1.BMCOM003' :data="formData1"  :createVars="createVars" />
        </div>
        <div
              class="topTitle"
              v-show="fileImgList?.length > 0"
            >
              附件
            </div>
            <div
              class="detailinlineStyle"
            >
              <span
                v-show="fileImgList?.length > 0"
                style="margin-right: 10px"
              >
                附件:
              </span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image
                      width="100"
                      height="100"
                      :src="i.url"
                      :key="i.id"
                      v-for="i in fileImgList"
                    />
                  </n-space>
                </n-image-group>
              </div>
            </div>
              <!-- <DynamicPageForm
                ref="formInst"
                :form-model="otherJson"
                :model="formData1"
                disabled
                :form-data="formData1"
                label-placement="left"
                require-mark-placement="left"
                label-width="140"
              /> -->
              <div>
                <div class="topTitle">审批信息</div>
                <div class="approve">
                  <div class="box">
                    <span>审批状态</span>
                    <span>{{ form?.status }}</span>
                  </div>
                  <div class="box">
                    <span>审批流程</span>
                    <span>{{ form?.workflow || '--' }}</span>
                  </div>
                </div>
                <div class="topTitle">审批记录</div>
                <div class="table">
                  <NDataTable
                    :bordered="false"
                    :columns="columns1"
                    :data="tableData1"
                    :pagination="false"
                    striped
                  />
                </div>
              </div>
              <!--  -->
              <!-- 终审显示 -->
              <div class="br"></div>
              <!-- <div v-if="route.query?.typeShow == 2">
              <div class="topTitle">终审信息</div>
              <div class="approve">
                <div class="box">
                  <span>审批状态</span>
                  <span>{{ form?.status1 }}</span>
                </div>
                <div class="box">
                  <span>审批流程</span>
                  <span>{{ form?.workflow1 || '--' }}</span>
                </div>
              </div>
              <div class="topTitle">终审记录</div>
              <div class="table">
                <NDataTable
                  :bordered="false"
                  :columns="columns1"
                  :data="tableData2"
                  :pagination="false"
                  striped
                />
              </div>
            </div> -->
            </div>
          </NSpin>
        </NScrollbar>
      </div>
   <NModal
                :auto-focus="false"
                v-model:show="modalVisible"
              >
                <VDialogContent
                  @close="modalVisible = false"
                  @submit="againBack"
                  title="审核退回"
                >
                  <div style="display: flex; width: 400rem">
                    <span style="color: red">*</span>
                    审核退回: 
                    <NInput
                      v-model:value="form.remarkResult"
                      type="textarea"
                      placeholder="审核退回"
                      style="width: 288rem; margin-left: 10px"
                      rows="5"
                    />
                  </div>
                </VDialogContent>
              </NModal>
    </div>
  </DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .dynamic-form-demo {
    background-color: #e1e1e1;
    padding: 30px 45px 10px;
    // height:300px;
  }
  .detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 45px;
}
  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }

  .approve {
    display: flex;
    width: 100%;
    margin-bottom: 20rem;
    border-bottom: 1px dashed #bc9e70;

    .box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 100rem;
      width: auto;
      height: 90rem;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      padding: 12rem;
      margin-right: 10rem;
      margin-bottom: 20rem;

      span:first-child {
        font-size: 16rem;
      }

      span:last-child {
        font-weight: 500;
        color: #5fb17f;
      }
    }
  }
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
